<template>
    <div v-if="fildList && fildList.length > 0">
        <!-- 都是图片且数量小于等于3显示图片 -->
        <div
            v-if="props.listCard && isOnlyImage && imagesDataList.length <= 3"
            v-viewer
            class="flex p-tb-10"
        >
            <div class="imgbox" v-for="item in imagesDataList">
                <img class="pointer" :src="item.url" :key="item.url" />
            </div>
        </div>
        <div
            v-else
            v-for="(item, index) of fildList"
            @click="doPreview(item, index)"
            class="pointer el-color-primary"
            style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            "
        >
            <span v-if="showIndex">{{ index + 1 }}、 </span>{{ item.name }}
        </div>
    </div>
    <div v-else>{{ props.emptyText || '暂未上传' }}</div>
</template>

<script setup>
import { api as viewerApi } from 'v-viewer'
import { getFileExtName, getFileName } from '@/utils'
import { computed, useAttrs } from 'vue'
const imageType = ['jpg', 'jpeg', 'png']
const attrs = useAttrs()

const props = defineProps({
    formData: {
        type: Object,
        default: () => ({})
    },
    listCard: {
        type: Boolean,
        default: true
    },
    showIndex: {
        type: Boolean,
        default: false
    },
    emptyText: {
        type: String,
        default: ''
    }
})

const fildList = computed(() => {
    return props.formData[attrs.prop]?.map((i) => {
        return {
            url: i.url,
            name: i.name || getFileName(i.url)
        }
    })
})

// 图片的集合
const imagesDataList = computed(() => {
    return fildList.value?.filter((i) =>
        imageType.includes(getFileExtName(i.name).toLowerCase())
    )
})

const imageList = computed(() => {
    return imagesDataList.value?.map((i) => i.url)
})

// 是否都是图片
const isOnlyImage = computed(() => {
    return (
        fildList.value?.length === imagesDataList.value?.length &&
        fildList.value?.length > 0
    )
})

// 预览图片和文件
const doPreview = (previewData, index) => {
    if (
        imageType.includes(
            getFileExtName(getFileName(previewData.name)).toLowerCase()
        )
    ) {
        viewerApi({
            images: imageList.value,
            options: {
                initialViewIndex: imageList.value?.indexOf(previewData.url)
            }
        })
    } else {
        if (previewData && previewData.url) {
            window.open(previewData.url, '_blank')
        }
    }
}
</script>

<style lang="scss">
.imgbox {
    width: 80px;
    height: 80px;
    margin: 0 5px;
    overflow: hidden;
}
</style>
